<template>
  <div class="dashboard-container">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm"
             label-position="left">
      <el-row>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item label="课程名称：" prop="course_title">
              <el-input v-model="ruleForm.course_title" placeholder="请输入课程名称"></el-input>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item label="课程关键词：" prop="course_keywords">
              <el-input v-model="ruleForm.course_keywords" placeholder="请输入课程关键词"></el-input>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item label="课程费用：" prop="course_price">
              <el-input v-enter-number v-model="ruleForm.course_price" placeholder="请输入课程费用"></el-input>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <div class="grid-content bg-purple">
            <el-form-item label="排序：" prop="course_orderid">
              <el-input v-enter-number v-model.number="ruleForm.course_orderid" placeholder="请输入排序"></el-input>
            </el-form-item>
          </div>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="6">
          <el-form-item label="课程分类：" prop="course_parentid">
            <div class="grid-content bg-purple">
              <el-select @change="queryTwoLevel(ruleForm.course_parentid)" v-model="ruleForm.course_parentid" filterable
                         placeholder="一级分类">
                <el-option v-for="item in oneLevel" :key="item.id" :label="item.cat_name" :value="item.id">
                </el-option>
              </el-select>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label-width="0">
            <div class="grid-content bg-purple-light">
              <el-select @change="queryThreeLevel(ruleForm.course_secondid)" v-model="ruleForm.course_secondid==0?'':ruleForm.course_secondid"
                         filterable placeholder="二级分类">
                <el-option v-for="item in twoLevel" :key="item.id" :label="item.cat_name" :value="item.id">
                </el-option>
              </el-select>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label-width="0">
            <div class="grid-content bg-purple">
              <el-select v-model="ruleForm.course_catid==0?'':ruleForm.course_catid" filterable placeholder="三级分类">
                <el-option v-for="item in threeLevel" :key="item.id" :label="item.cat_name" :value="item.id">
                </el-option>
              </el-select>
            </div>
          </el-form-item>
        </el-col>
      </el-row>


      <div style="display: flex; width: 100%; margin-top: 15px;">
        <span style="display: flex; width: 80px; align-items: center; justify-content: left;font-size: 14px;
    color: #606266;">课程图：</span>
        <el-upload ref="upload" action="#"
                   :http-request="submitUpload"
                   :file-list="dataForm.imgFileList"
                   list-type="picture-card"
                   :on-preview="handlePictureCardPreview"
                   :on-change="OnChange"
                   :on-remove="handleRemove"
                   :on-exceed="handleExceed"
                   accept="image/jpeg,image/png">
          <i class="el-icon-plus"></i>
          <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，最多上传5张且单张图片不超过500kb
          </div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" append-to-body>
          <img width="100%" :src="dialogImageUrl">
        </el-dialog>
      </div>


      <el-form-item label="课程上课班制：" prop="course_class">
        <el-checkbox-group v-model="ruleForm.course_class">
          <el-checkbox label="脱产班" name="type"></el-checkbox>
          <el-checkbox label="业余班" name="type"></el-checkbox>
          <el-checkbox label="工作日班" name="type"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="课程类型" prop="course_type">
        <el-radio-group v-model="ruleForm.course_type">
          <el-radio label="3">面授课程</el-radio>
          <el-radio label="6">网络课程</el-radio>
          <el-radio label="9">上门辅导课程</el-radio>
          <el-radio label="12">vip一对一课程</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="课程周期" prop="course_time">
        <el-radio-group v-model="ruleForm.course_time">
          <el-radio label="3">1个月以内</el-radio>
          <el-radio label="6">1-3个月</el-radio>
          <el-radio label="9">3-6个月</el-radio>
          <el-radio label="12">6-12个月</el-radio>
          <el-radio label="15">一年以上</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-row>
        <el-col :span="20">
          <div class="grid-content bg-purple">
            <el-form-item label="机构简介：" prop="course_introduct">
              <el-input type="textarea" v-model="ruleForm.course_introduct"></el-input>
            </el-form-item>
          </div>
        </el-col>
      </el-row>
      <!--  <el-row>
          <el-col :span="20">
            <div class="grid-content bg-purple">
              <el-form-item label="课程详情：" prop="course_courseInfo">
                <el-input type="textarea" v-model="ruleForm.course_courseInfo"></el-input>
              </el-form-item>
            </div>
          </el-col>
        </el-row>-->


      <div class="table">
        <editor id="editor_id" height="600px" width="95%" :content.sync="ruleForm.course_courseInfo"
                :afterChange="afterChange()"
                pluginsPath="../../../../assets/kindeditor/plugins/"
                :loadStyleMode="false"
                @on-content-change="onContentChange"></editor>
      </div>


      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>

    <!--侧边栏内容-->
    <div class="mbys-box-right">
      <el-button @click="drawer = true" type="primary" style="margin-left: 16px;">
        样式栏目
        <i class="el-icon-caret-left"></i>
      </el-button>
      <el-drawer title="我是标题" :visible.sync="drawer" :with-header="false" size="50%">
        <div>
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="正文" name="first" lazy>
              <div v-for="(item,index) in mainBody" :key="index">
                <div @click="pushContent(editorText+item.style)">
                  <div v-html="item.style"></div>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="标题" name="second" lazy>
              <div v-for="(item,index) in title" :key="index">
                <div @click="pushContent(editorText+item.style)">
                  <div v-html="item.style"></div>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="图文" name="third" lazy>
              <div v-for="(item,index) in pic" :key="index">
                <div @click="pushContent(editorText+item.style)">
                  <div v-html="item.style"></div>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="js" name="fourth" lazy>
              <div v-for="(item,index) in js" :key="index">
                <div @click="pushContent(editorText+item.style)">
                  <div v-html="item.style"></div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script>

import {
  cateComList,
  courseStyle,
  schoolAdd,
  uploadImg,
  courseAdd,
  schoolInfo,
  courseInfo,
  courseEdit,
  delImg
} from "@/api/menu";
import {mapGetters} from 'vuex'

export default {
  data() {
    return {
      styleContent: '',
      mainBody: '',
      title: '',
      pic: '',
      js: '',
      tId: '',
      activeName: 'first',
      editorText: '', // 双向同步的变量
      editorTextCopy: '',// content-change 事件回掉改变的对象
      ruleForm: {
        course_title: '',
        course_schoolid: '',
        course_parentid: '',
        course_secondid: '',
        course_catid: '',
        course_orderid: '',
        course_keywords: '',
        course_price: '',
        course_class: [],
        course_type: '',
        course_time: '',
        course_introduct: '',
        course_courseInfo: '',
        course_images: []
      },
      rules: {
        course_title: [
          {required: true, message: '请输入课程名称', trigger: 'blur'}
        ],
        course_orderid: [
          {required: true, message: '请输入排序', trigger: 'blur'}
        ],
        course_keywords: [
          {required: true, message: '请输入课程关键词', trigger: 'blur'}
        ],
        course_price: [
          {required: true, message: '请输入课程费用', trigger: 'blur'}
        ],
        course_parentid: [
          {required: true, message: '请选择课程一级分类', trigger: 'change'}
        ],
        /* course_secondid: [
           {required: true, message: '请选择课程二级分类', trigger: 'change'}
         ],
         course_catid: [
           {required: true, message: '请选择课程三级分类', trigger: 'change'}
         ],*/
        course_class: [
          {required: true, message: '请选择一个课程上课班制', trigger: 'change'}
        ],
        course_type: [
          {required: true, message: '请选择一个课程类型', trigger: 'change'}
        ],
        course_time: [
          {required: true, message: '请选择一个课程周期', trigger: 'change'}
        ],
        course_introduct: [
          {required: true, message: '请输入机构简介', trigger: 'blur'}
        ],
        course_courseInfo: [
          {required: true, message: '请输入课程详情', trigger: 'blur'}
        ]
      },
      drawer: false,
      oneLevel: [],
      twoLevel: [],
      threeLevel: [],
      dialogImageUrl: '',
      dialogVisible: false,
      picList: [],
      fileList: [],
      fileList_now: [],
      hideUpload: false, //是否显示上传图片的加号
      imgInfoList: [], //包含图片的id,name,size的集合
      imgNameList: [], //后端返回的上传图片的name集合，传到后端
      imgSize: [], //后端返回的上传图片的imgSize集合，传到后端
      deleteImgFileList: [], //存已被删除了的图片的id
      dataForm: {
        imgFileList: []//绑定用户上传的图片List
      },
      imgUrl: [],
    }
  },
  computed: {

  },
  mounted() {
    courseStyle({typeid: 'a'}).then(response => {
      console.log(response);
      this.mainBody = response.data
    });
    this.getOneLevel()
    this.getInfo()
  },
  methods: {
    //点击上传图片
    submitUpload() {
      let formData = new FormData(); //  用FormData存放上传文件
      this.dataForm.imgFileList.forEach(file => {
        formData.append('file', file.raw)
      })
      uploadImg(formData).then(response => {
        console.log(response);
        this.dialogImageUrl = response.data;
        this.ruleForm.course_images.push(response.data);
        console.log(this.ruleForm.course_images);
      })
    },
    //预览图片时
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    OnChange(file, fileList) {
      const isLt1M = file.size / 1024 / 1024 / 0.5 < 1
      console.log(isLt1M);
      if ( !isLt1M ) {
        this.$message.error('上传头像图片大小不能超过 500kb!');
        fileList.pop()
      }
      this.dataForm.imgFileList.push(file)
      this.hideUpload = fileList.length >= this.limit

    },
    //删除图片时
    handleRemove(file, fileList) {
      console.log(file);
      console.log(fileList);
      if ( file.id ) {
        console.log('删除了已被上传过的图片')
        console.log(file.id)
        this.deleteImgFileList.push(file.id)
      }
      this.dataForm.imgFileList = fileList
      this.hideUpload = fileList.length >= this.limit
      /**
       * 删除图片
       */
      delImg({
        imgUrl:file.url
      }).then(response => {
        console.log(response);
      })
    },
    /**
     * 详情
     */
    getInfo() {
      courseInfo(this.$route.query.rowId).then(response => {
        console.log(response);
        this.ruleForm = response.data;
        this.imgUrl = response.data.course_images;
        this.imgUrl.forEach(item => {
          let obj = new Object();
          obj.url = item;
          this.dataForm.imgFileList.push(obj);
        });
        cateComList({
          cate_parentid: this.ruleForm.course_parentid,
          cate_secondid: 0
        }).then(response => {
          console.log(response);
          this.twoLevel = response.data
        })
        cateComList({
          cate_parentid: this.ruleForm.course_secondid,
          cate_secondid: this.ruleForm.course_parentid
        }).then(response => {
          console.log(response);
          this.threeLevel = response.data
        })
      });
    },
    /**
     * 查询二级数据
     */
    queryTwoLevel(value) {
      console.log(value);
      this.ruleForm.course_secondid = '';
      this.ruleForm.course_catid = '';
      cateComList({
        cate_parentid: value,
        cate_secondid: 0
      }).then(response => {
        console.log(response);
        this.twoLevel = response.data
        this.twoLevel.unshift({id: "", cat_name: "请选择"})
      })
    },
    /**
     * 查询三级数据
     */
    queryThreeLevel(value) {
      this.ruleForm.course_catid = '';
      console.log(value);
      cateComList({
        cate_parentid: value,
        cate_secondid: this.ruleForm.course_parentid
      }).then(response => {
        console.log(response);
        this.threeLevel = response.data
        this.threeLevel.unshift({id: "", cat_name: "请选择"})
      })
    },
    /**
     * 获取一级数据
     */
    getOneLevel() {
      cateComList({
        cate_parentid: 0,
        cate_secondid: 0
      }).then(response => {
        console.log(response);
        this.oneLevel = response.data
        this.oneLevel.unshift({id: "", cat_name: "请选择"})
      })
    },
    handleClick(tab, event) {
      if ( tab.label == '正文' ) {
        courseStyle({typeid: 'a'}).then(response => {
          console.log(response);
          this.mainBody = response.data
        });
      } else if ( tab.label == '标题' ) {
        courseStyle({typeid: 'b'}).then(response => {
          console.log(response);
          this.title = response.data
        });
      } else if ( tab.label == '图文' ) {
        courseStyle({typeid: 'c'}).then(response => {
          console.log(response);
          this.pic = response.data
        });
      } else if ( tab.label == 'js' ) {
        courseStyle({typeid: 'd'}).then(response => {
          console.log(response);
          this.js = response.data
        });
      }
    },
    onContentChange(val) {
      this.editorText = val;
      console.log(val)
      this.ruleForm.course_courseInfo = val
    },
    afterChange(val) {

    },
    /**
     * 修改
     * @param formName
     */
    submitForm(formName) {
      this.$refs[ formName ].validate((valid) => {
        if ( valid ) {
          courseEdit(Object.assign(this.ruleForm, {id: this.$route.query.rowId})).then(response => {
            this.listLoading = false;
            console.log(response);
            this.$message({message: '修改成功', type: 'success', duration: 1000});
            this.$router.push({path: '/classList', query: {id: this.$route.query.id}});
          });
        } else {
          console.log(this.editorText);
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[ formName ].resetFields();
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 5 个课程图`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    pushContent(item) {
      this.onContentChange(item)
    }
  }
}
</script>

<style scoped>
/deep/ .el-drawer {
  overflow-y: scroll;
}

.table {
  margin-bottom: 20px;
}

.my /deep/ .el-radio__inner {
  width: 18px;
  height: 18px;
}

.my /deep/ .el-radio__inner::after {
  width: 6px;
  height: 6px;
}

.small-button /deep/ .el-upload-list {
  display: none;
}

.mbys-box-right /deep/ .el-button {
  margin-left: 0px !important;
  height: 100%;
  background-color: #1f2d3d;
  border-color: #1f2d3d;
  border-radius: 0px;
  white-space: inherit;
}

.mbys-box-right /deep/ .el-button span {
  display: block;
  width: 15px;
  font-weight: bold;
  line-height: 25px;
  word-wrap: break-word;
  word-break: break-all;
  position: relative;
}
</style>
<style lang="scss" scoped>
.el-icon-caret-left {
  position: absolute;
  top: 20%;
  left: -65px;
  font-size: 80px;
  color: #1f2d3d;
}

.mbys-box-right {
  position: absolute;
  top: 0px;
  right: 0px;
  height: 100%;
}

.div-button {
  width: 10%;
}

.div-button:nth-child(2) {
  margin-left: 100px;
}

.dashboard-box-auto, .dashboard-box-bottom {
  margin-top: 15px;
}

.dashboard-container ul {
  margin: 0px;
  padding: 0px;
}

.dashboard-container li {
  list-style: none;
}

.dashboard-box-right > ul {
  font-size: 0;
  width: 100%;
}

.dashboard-box-right > ul > li:nth-child(1) {
  display: block;
  width: 100%;
  margin: 0;
  border: 5px solid #cccccc;
}

.dashboard-box-right > ul > li:nth-child(2) {
  margin-left: 0;
}

.dashboard-box-right > ul > li {
  width: 22%;
  font-size: 0;
  margin-left: 4%;
  margin-top: 15px;
  border: 3px solid #cccccc;
  display: inline-block;
}

.dashboard-box-right > ul > li > img {
  width: 100%;
}

.el-checkbox.is-bordered {
  margin: 0px;
}

.el-select {
  width: 100%;
}

.dashboard-box-top {
  display: flex;
}

.dashboard-box-left {
  width: 50%;
}

.dashboard-box-right {
  width: 26%;
  margin-left: 10%;
}

.el-radio {
  &-inner {
    width: 18px;
    height: 18px;
  }
}

.dashboard {
  &-container {
    margin: 0 15px;
    padding: 30px;
    position: relative;
    background-color: #fff;
  }

  &-text {
    font-size: 16px;
  }
}
</style>
